package com.power.sifa.approve.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.SpringHolder;
import com.plf.core.common.file.FileController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.power.sifa.approve.model.Apl_thirdper;
import com.power.sifa.approve.model.pageInfo.Apl_thirdperPageInfo;
import com.power.sifa.approve.api.IApl_thirdperFeign;
import com.power.sifa.approve.service.Apl_thirdperService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;



/**
 *   第三人控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Apl_thirdperController",tags={"第三人"})
public class Apl_thirdperController implements IApl_thirdperFeign{

    @Resource
    private Apl_thirdperService apl_thirdperService;

    @Override
    @ApiOperation("查询第三人分页列表")
    @SaCheckPermission("apl_thirdper_list")
    public ResponseDTO list(Apl_thirdperPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Apl_thirdper> page = this.apl_thirdperService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Apl_thirdper apl_thirdper : page) {
                apl_thirdper.geneText();
                list.add(apl_thirdper);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看第三人")
    @SaCheckPermission("apl_thirdper_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Apl_thirdper apl_thirdper  = apl_thirdperService.getById(id);
        if (apl_thirdper != null) {
            apl_thirdper.geneText();
        }
        return ResponseDTO.succData(apl_thirdper);
    }

    @Override
    @ApiOperation("删除第三人")
    @SaCheckPermission("apl_thirdper_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        apl_thirdperService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改第三人")
    @SaCheckPermission("apl_thirdper_save")
    public ResponseDTO save(Apl_thirdper apl_thirdper) {
        Assert.notNull(apl_thirdper, "apl_thirdper不能为空");
        apl_thirdperService.saveOrUpdate(apl_thirdper);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="批量删除第三人")
    @SaCheckPermission("apl_thirdper_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.isNotEmpty(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        apl_thirdperService.removeByIds(list);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("apl_thirdper_list")
    public void output(HttpServletResponse response, Apl_thirdperPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "第三人";
        String[] heads = {"applyid+nanoid","applyid","第三人类型","名称","证件类型","证件号","联系地址","联系电话","邮政编码","法定代表人或主要负责人","工作单位","民族","性别","职务","排序","代理人id","出生年月","附件id"};
        String[] fields = {"id","applyid","type","name","cardtype","cardno","addr","tel","postcode","manager","unit","nation","gender","job","sortnum","agentid","birthym","attachid"};
        Page<Apl_thirdper> page = this.apl_thirdperService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }
            
    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "第三人";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"applyid+nanoid","applyid","第三人类型","名称","证件类型","证件号","联系地址","联系电话","邮政编码","法定代表人或主要负责人","工作单位","民族","性别","职务","排序","代理人id","出生年月","附件id"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }
    
	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","applyid","type","name","cardtype","cardno","addr","tel","postcode","manager","unit","nation","gender","job","sortnum","agentid","birthym","attachid"};
        List<Apl_thirdper> list = (List<Apl_thirdper>)ExcelUtil.Import(fields, file, Apl_thirdper.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.apl_thirdperService.saveAll(list);
        }
        return ResponseDTO.succ();
	}


    /**
     * 更新附件id
     * @param id 主键id
     * @param type 类型：0：身份证明 1:身份证明书，2：第三人证明材料
     * @param attachId 附件id
     * @return
     */
    @Override
    public ResponseDTO updateAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_thirdper apl_thirdper = this.apl_thirdperService.getById(id);
            switch (type) {
                case 0:
                    apl_thirdper.setFilecard(attachId);
                    break;
                case 1:
                    apl_thirdper.setDoccard(attachId);
                    break;
                case 2:
                    apl_thirdper.setThirdevidence(attachId);
                    break;
                default:
                    break;
            }
            this.apl_thirdperService.saveOrUpdate(apl_thirdper);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "更新附件id失败");
        }
    }

    /**
     * 删除附件id
     * @param id 主键id
     * @param type 类型：0：身份证明 1:身份证明书，2：第三人证明材料
     * @param attachId 附件id
     * @return
     * @return
     */
    @Override
    public ResponseDTO deleteAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_thirdper apl_thirdper = this.apl_thirdperService.getById(id);
            // 删除文件
            FileController fileController = SpringHolder.getBean(FileController.class);
            fileController.minioRemove(null,attachId);
            switch (type) {
                case 0:
                    String filecardId = apl_thirdper.getFilecard();
                    if (StringUtils.isNotEmpty(filecardId)) {
                        List<String> restFileIds = Arrays.asList(filecardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restFileIds)) {
                            apl_thirdper.setFilecard(null);
                        }
                        apl_thirdper.setFilecard(String.join(",", restFileIds));
                    }
                    break;
                case 1:
                    String doccardId = apl_thirdper.getDoccard();
                    if (StringUtils.isNotEmpty(doccardId)) {
                        List<String> restDocIds = Arrays.asList(doccardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restDocIds)) {
                            apl_thirdper.setDoccard(null);
                        }
                        apl_thirdper.setDoccard(String.join(",", restDocIds));
                    }
                    break;
                case 2:
                    String thirdEvidenceId = apl_thirdper.getThirdevidence();
                    if (StringUtils.isNotEmpty(thirdEvidenceId)) {
                        List<String> thirdEvidenceIds = Arrays.asList(thirdEvidenceId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(thirdEvidenceIds)) {
                            apl_thirdper.setDoccard(null);
                        }
                        apl_thirdper.setDoccard(String.join(",", thirdEvidenceIds));
                    }
                    break;
                default:
                    break;
            }
            this.apl_thirdperService.saveOrUpdate(apl_thirdper);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "删除附件失败");
        }
    }

    /**
     * 通过applyid查询对应的第三人数据
     * @param applyid
     * @return
     */
    @Override
    public ResponseDTO getThirdWithGroup(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_thirdperService.getThirdWithGroup(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    /**
     * 第三人查询 全部查询
     */
    @Override
    public ResponseDTO getThirdByApplyid(String applyid) {
        try {
            List<Apl_thirdper>  thirdperList = this.apl_thirdperService.getThirdListByApplyid(applyid);
            if (CollectionUtil.isNotEmpty(thirdperList)) {
                for (Apl_thirdper apl_thirdper : thirdperList) {
                    apl_thirdper.geneText();
                }
            }
            return ResponseDTO.succData(thirdperList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    /**
     * 第三人名称查询
     */
    @Override
    public ResponseDTO searchByName(String name) {
        try {
            List<Apl_thirdper> thirdperList = this.apl_thirdperService.searchByName(name);
            if (CollectionUtil.isNotEmpty(thirdperList)) {
                for (Apl_thirdper apl_thirdper : thirdperList) {
                    apl_thirdper.geneText();
                }
            }
            return ResponseDTO.succData(thirdperList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    @Override
    public ResponseDTO getUnSaveThirdWithGroup(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_thirdperService.getUnSaveThirdWithGroup(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }


}
